package com.ctcemti.mdm.common.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JWTUtil {
    public static final String SECRET_KEY = "CECT_GLYJY"; //秘钥
    public static final long TOKEN_EXPIRE_TIME = 30 * 60 * 1000; //token过期时间
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 5 * 60 * 1000; //refreshToken过期时间
    private static final String ISSUER = "ctceadminstrator"; //签发人
    private static final long ADVANCE_EXPIRE_TIME = 5 * 60 * 1000; //token过期时间

    /* *
     * @Author bxf
     * @Description 生成签名
     * @Date 8:25 2019/8/27
     * @param loginName
     * @param loginId
     * @return java.lang.String
     */
    public static String generateToken(String loginName,String loginId){
        Date now = new Date();
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法
        String token = JWT.create()
                .withIssuer(ISSUER) //签发人
                .withIssuedAt(now) //签发时间
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME)) //过期时间
                .withClaim("loginName", loginName) //保存登录名
                .withClaim("loginId", loginId) //保存身份标识
                .sign(algorithm);
        return token;
    }

    /* *
     * @Author bxf
     * @Description 重新生成签名
     * @Date 8:26 2019/8/27
     * @param access_token
     * @return java.lang.String
     */
    public static String reGenerateToken(String access_token){
        String loginName = JWT.decode(access_token).getClaim("loginName").asString();
        String loginId= JWT.decode(access_token).getClaim("loginId").asString();
        Date now = new Date();
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法
        String token = JWT.create()
                .withIssuer(ISSUER) //签发人
                .withIssuedAt(now) //签发时间
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME)) //过期时间
                .withClaim("loginName", loginName) //保存登录名
                .withClaim("loginId", loginId) //保存身份标识
                .sign(algorithm);
        return token;
    }

    /* *
     * @Author bxf
     * @Description 验证token
     * @Date 8:26 2019/8/27
     * @param token
     * @return boolean
     */
    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception ex){
            ex.printStackTrace();
        }
        return false;
    }

    /* *
     * @Author bxf
     * @Description 从token获取loginName
     * @Date 8:26 2019/8/27
     * @param token
     * @return java.lang.String
     */
    public static String getLoginName(String token){
        try{
            return JWT.decode(token).getClaim("loginName").asString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return "";
    }

    /* *
     * @Author bxf
     * @Description 从request获取loginName
     * @Date 8:26 2019/8/27
     * @param token
     * @return java.lang.String
     */
    public static String getLoginName(HttpServletRequest request){
        try{
            String token = request.getHeader("Authorization");
            return JWT.decode(token).getClaim("loginName").asString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return "";
    }
    /* *
     * @Author bxf
     * @Description 从token获取参数param
     * @Date 8:27 2019/8/27
     * @param token
     * @param param
     * @return java.lang.String
     */
    public static String getParam(String token,String param){
        try{
            return JWT.decode(token).getClaim(param).asString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return "";
    }
    /* *
     * @Author bxf
     * @Description 从token获取loginId
     * @Date 8:26 2019/8/27
     * @param token
     * @return java.lang.String
     */
    public static String getLoginId(String token){
        try{
            return JWT.decode(token).getClaim("loginId").asString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return "";
    }

    /* *
     * @Author bxf
     * @Description 从request获取loginId
     * @Date 8:26 2019/8/27
     * @param token
     * @return java.lang.String
     */
    public static String getLoginId(HttpServletRequest request){
        try{
            String token = request.getHeader("Authorization");
            return JWT.decode(token).getClaim("loginId").asString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 检查当前token是否还能继续使用
     * true：可以  false：不建议
     * @param token
     * @return
     */
    public static boolean checkToken(String token){
        try {
            // jwt正常情况 则判断失效时间是否大于5分钟
            long expireTime = JWT.decode(token).getExpiresAt().getTime();
            long diff = expireTime - System.currentTimeMillis();
            System.out.print(diff);
            //如果有效期小于5分钟，则不建议继续使用该token
            if (diff < ADVANCE_EXPIRE_TIME) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static void main1(String[] args) {
        //System.out.println(generateToken("小明","123456"));
        System.out.println(getLoginId("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbklkIjoiMTIzNDU2IiwibG9naW5OYW1lIjoi5bCP5piOIiwiaXNzIjoiY3RjZWFkbWluc3RyYXRvciIsImV4cCI6MTU2NjgwMTkyMCwiaWF0IjoxNTY2ODAxNjIwfQ.m1LU2KRoJERPZfxnEbQct7lpT_RqZbR_m9pWLjUvhbM"));
    }

}
